import 'package:flutter_note/entity/note.dart';
import 'package:logger/logger.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DbHelper {
  static Database _db;
  static DbHelper _instance;
  var logger = Logger();

  factory DbHelper() => _getInstance();

  static DbHelper _getInstance() {
    if (_instance == null) {
      _instance = DbHelper._internal();
    }
    return _instance;
  }

  static DbHelper get instance => _getInstance();

  DbHelper._internal() {
    /* getDatabasesPath().then((path) async {
      _db = await openDatabase(path, version: 1, onCreate: _onCreate);
    });*/
    // _initDb();
    //_db = initDb();
  }

  static _initDb() async {
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, 'note.db');
    _db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('create table if not exists $tableNote('
          '$columnId integer primary key autoincrement,'
          '$columnContent text not null,'
          '$columnTs integer not null)');
    });
    //  return ourDb;
  }

  static Future<Database> getCurrentDb() async {
    if (_db == null) {
      await _initDb();
    }
    return _db;
  }

/*  void _onCreate(Database db, int version) async {
    await db.execute('create table $tableNote('
        '$columnId integer primary key autoincrement,'
        '$columnContent text not null,'
        '$columnTs integer not null)');
  }*/

  Future<Note> insert(Note note) async {
    Database database = await getCurrentDb();
    note.id = await database.insert(tableNote, note.toMap());
    return note;
  }

  Future<Note> queryNote(int id) async {
    Database database = await getCurrentDb();
    List<Map> maps = await database.query(tableNote,
        columns: [columnId, columnContent, columnTs],
        where: '$columnId = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      return Note.fromMap(maps.first);
    }
    return null;
  }

  Future<List<Note>> queryAll() async {
    logger.d("---------queryAll---------");
    Database database = await getCurrentDb();
    return Note.fromList(await database.rawQuery('select * from $tableNote order by $columnTs desc'));
  }

  Future<int> delete(int id) async {
    Database database = await getCurrentDb();
    return await database
        .delete(tableNote, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> update(Note note) async {
    Database database = await getCurrentDb();
    return await database.update(tableNote, note.toMap(),
        where: '$columnId = ?', whereArgs: [note.id]);
  }

  static close() {
    _db?.close();
    _db = null;
  }
}
